package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.SysContracts;
import com.ruoyi.system.domain.SysUserScok;
import com.ruoyi.system.domain.vo.Orders;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class TCPClient {
    public static void tcpClient(SysContracts contracts) {
        try {
            // 创建TCP客户端并连接到服务器
            String serverAddress = "127.0.0.1";
            int serverPort = 8888;
            Socket clientSocket = new Socket(serverAddress, serverPort);
//            Orders orders = new Orders(contracts.getId(), contracts.getStockId(), contracts.getUserId(), contracts.getUname(), contracts.getScokName(), contracts.getScokPrice(), contracts.getNum(), contracts.getStatus(), contracts.getIndate(), contracts.getFalg());


            // 创建输入流和输出流
            InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();
            String data = JSONObject.toJSONString(contracts); //将数据json化
            String key = "1234567890123456"; // 16字节密钥
            // 加密
            String encryptedData =encrypt(data, key)+"*xy*"; //在密文后添加分隔符,防止粘包
            System.out.println(encryptedData);

            // 发送数据给服务器
            outputStream.write(encryptedData.getBytes(StandardCharsets.UTF_8));
            // 读取服务器响应的数据
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream.read(buffer);
            String receivedMessage = new String(buffer, 0, bytesRead);
            System.out.println("收到服务器响应：" + receivedMessage);
            // 关闭连接
//            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//  加密
    private static String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

}
